package tcu.ead2021.leety.iotsystem_mqtt.common.utils.mqttutils;

import java.sql.*;

public class SQLUtils {
    /**
     * 采用了JDBC方法，检测是否在数据库中存在TableName表
     * 若没有，则创建数据表
     * 若有，则跳出
     */
    public static void initTable(String TableName) throws SQLException, ClassNotFoundException {

        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection conn = DriverManager.getConnection("jdbc:mysql://82.156.22.86:3306/tcu", "root", "2021TcuTree.");
        Statement stat = conn.createStatement();

        //判断是否在数据库中有TableName表
        ResultSet rs = conn.getMetaData().getTables(null, null, TableName, null);
        if (rs.next()) {
            return;
        } else {
            stat.executeUpdate("CREATE TABLE `" + TableName + "` (\n" +
                    "  `time` varchar(255) NOT NULL,\n" +
                    "  `template` varchar(255) DEFAULT NULL,\n" +
                    "  `power` int(11) DEFAULT NULL,\n" +
                    "  `I1` float DEFAULT NULL,\n" +
                    "  `I2` float DEFAULT NULL,\n" +
                    "  `I3` float DEFAULT NULL,\n" +
                    "  `I4` float DEFAULT NULL,\n" +
                    "  PRIMARY KEY (`time`)\n" +
                    ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        }

        stat.close();
        conn.close();
        rs.close();
    }
}
